package com.easy.admin.system.test.netty.chat;

import cn.hutool.core.date.DateUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @author wangbo
 * @deprecated netty server for chat
 *
 */
public class ChatServer {

    private int port;

    public ChatServer(int port){
        this.port = port;
    }

    public void runServer(){
        EventLoopGroup groupC = new NioEventLoopGroup();
        EventLoopGroup groupW = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        Channel channe=null;
    try {
        bootstrap.group(groupC, groupW)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline cp = socketChannel.pipeline();
                        cp.addLast("decoder", new StringDecoder());
                        cp.addLast("encoder", new StringEncoder());
                        cp.addLast(new ChatServerHandler());
                    }
                });
        ChannelFuture cf = bootstrap.bind(this.port).sync();
        System.out.println("------------Server start ["+ DateUtil.date() +"]---------");
        cf.channel().closeFuture().sync();
    }catch (Exception e){
        e.printStackTrace();
    }
    finally {
        try {
            groupC.shutdownGracefully();
            groupW.shutdownGracefully();
          //  channe.closeFuture().sync();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    }
}
